﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using QWeiBoN.ViewModule;
using TencentWeiboSDK.Model;
using System.Windows.Media.Imaging;
using QWeiBoN.Objects;
using QWeiBo.ViewModule;
using QWeiBoN.Util;

namespace QWeiBoN.UserControler
{
    public partial class UserDetailView : PhoneApplicationPage
    {

        #region 私有属性

        private bool isLintener = false;

        private string openId;

        private User user;

        private List<Status> statusList;

        private AddFriendModel afModel = new AddFriendModel();

        private MainUserModel muModel = new MainUserModel();

        private MainListModel mlModel = new MainListModel();

        /// <summary>
        /// 拉取数据类型
        /// </summary>
        private enum EPollType
        {
            /// <summary>
            /// 默认，结果绑定到控件
            /// </summary>
            Default,
            /// <summary>
            /// 下一页，结果追加到末尾
            /// </summary>
            NextPage,
            /// <summary>
            /// 最新，结果插到开头
            /// </summary>
            Lastest
        }

        /// <summary>
        /// 加载数据的类型
        /// </summary>
        private EPollType pollType { get; set; }

        /// <summary>
        /// 是否正在拉取数据
        /// </summary>
        private bool isPolling { get; set; }

        /// <summary>
        /// 最后一条微博的时间戳
        /// </summary>
        private long lastTimestamp { get; set; }
        /// <summary>
        /// 第一条微博的时间戳
        /// </summary>
        private long firstTimestamp { get; set; }

        /// <summary>
        /// 最后一次刷新的时间
        /// </summary>
        private DateTime lastPollTime { get; set; }

        /// <summary>
        /// 手势是否是垂直拖拽
        /// </summary>
        private bool isVerticalDrag { get; set; }

        #endregion

        public UserDetailView()
        {
            InitializeComponent();
        }

        #region 导航处理

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // 清理上次的内容
            DetailUserNickText.Text = string.Empty;
            DetailUserVipImg.Visibility = Visibility.Collapsed;
            DetailUserNameText.Text = string.Empty;
            BitmapImage source = new BitmapImage();
            source.UriSource = new Uri("/Resources/noHead.png", UriKind.Relative);
            DetailUserHeadImg.Source = source;

            UserDetailItemGrid.DataContext = null;
            UserDetailItemGrid.UpdateLayout();
            UserDetailStatusList.ItemsSource = null;
            UserDetailStatusList.UpdateLayout();

            if (NavigationContext.QueryString.ContainsKey(AppSetting.UserNameKey))
            {
                openId = NavigationContext.QueryString[AppSetting.UserNameKey];
                if (!string.IsNullOrWhiteSpace(openId))
                {

                }
            }
            else
            {
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
        }

        #endregion

        #region 数据请求

        /// <summary>
        /// 用于得到用户信息
        /// </summary>
        private void RefreshUserInfo()
        {
            HeadPanelProgressBar.IsIndeterminate = true;
            muModel.getUserInfo(openId, callback =>
            {
                user = callback.Data;

                Dispatcher.BeginInvoke(() =>
                {
                    DetailUserNickText.Text = user.Nick;
                    DetailUserNameText.Text = user.Name;

                    UserDetailItemGrid.DataContext = user;
                    UserDetailItemGrid.UpdateLayout();
                    if (!string.IsNullOrWhiteSpace(user.Head))
                    {
                        string imageUri = callback.Data.Head.Substring(0, callback.Data.Head.Length - 2);
                        ImageSource source = new BitmapImage(new Uri(imageUri + "/100", UriKind.Absolute));
                        DetailUserHeadImg.Source = source;
                    }
                    if (user.IsVIP == 1)
                    {
                        DetailUserVipImg.Visibility = Visibility.Visible;
                    }

                    HeadPanelProgressBar.IsIndeterminate = false;
                });
            });
        }

        /// <summary>
        /// 用于拉取用户发表时间线
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="pagetime"></param>
        private void RefreshTimeLine(PageFlag flag, long pagetime)
        {
            lastPollTime = DateTime.Now;
            mlModel.RefreshUserTimeLine(flag, pagetime, openId, (callback) =>
            {
                var newData = new List<Status>();
                callback.Data.ForEach(a =>
                {
                    DateTime date = new DateTime(1970, 01, 01, 00, 00, 00);
                    date = date.AddSeconds(a.Timestamp);
                    a.From = date.Month + "月" + date.Day + "日 " + date.Hour + ":" + date.Minute + "  " + a.From;
                    if (null == a.Head || a.Head.Equals(""))
                    {
                        a.Head = "Resources/head_50.jpg";
                    }
                    switch (a.Type)
                    {
                        case 2:
                            //a.Nick = a.Nick + " 转播：";
                            a.Nexttime = " 转播：";
                            break;
                        case 3:
                            //a.Nick = a.Nick + " 私信：";
                            a.Nexttime = " 私信：";
                            break;
                        case 6:
                            //a.Nick = a.Nick + " 提及：";
                            a.Nexttime = " 提及：";
                            break;
                        default:
                            //a.Nick = a.Nick + "：";
                            a.Nexttime = "：";
                            break;
                    }
                    newData.Add(a);
                });

                var data = (IEnumerable<Status>)UserDetailStatusList.ItemsSource;
                if (pollType == EPollType.NextPage)
                {
                    data = data.Concat(newData).ToList();
                }
                else if (pollType == EPollType.Lastest)
                {
                    newData = newData.Where(t => t.Timestamp > firstTimestamp).ToList();
                    if (newData.Count > 0)
                    {
                        data = newData.Concat(data).ToList();
                    }
                }
                else
                {
                    data = newData;
                }
                if (data != null && data.Count() > 0)
                {
                    lastTimestamp = data.LastOrDefault().Timestamp;

                    firstTimestamp = data.FirstOrDefault().Timestamp;
                }
                UserDetailStatusList.ItemsSource = data;
                UserDetailStatusList.UpdateLayout();
            });
        }

        #endregion

        #region 事件处理

        /// <summary>
        /// 返回按钮的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserDetailBackBarBtn_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        /// <summary>
        /// 主页按钮的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HomeBackBarBtn_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        /// <summary>
        /// 收听/取消收听按钮的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserListenBarBtn_Click(object sender, EventArgs e)
        {
            if (isLintener) //已经收听进行取消收听处理
            {
                afModel.addFriend(openId, (callBack) =>
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        if (null == callBack.InnerException)
                        {
                            UserListenBarBtn.Text = "取消收听";
                        }
                        else
                        {
                            MessageBox.Show(callBack.InnerException.Message);
                        }
                    });
                });
            }
            else //未收听进行收听处理
            {
                afModel.delFriend(openId, (callBack) =>
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        if (null == callBack.InnerException)
                        {
                            UserListenBarBtn.Text = "收听";
                        }
                        else
                        {
                            MessageBox.Show(callBack.InnerException.Message);
                        }
                    });
                });
            }
        }

        /// <summary>
        /// Panorama选项改变事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Panorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (UserInfoPanorama.SelectedIndex == 0)
            {
                if (null == UserDetailItemGrid.DataContext)
                {
                    RefreshUserInfo();
                }
            }
            if (UserInfoPanorama.SelectedIndex == 1)
            {
                if (null == UserDetailStatusList.ItemsSource)
                {
                    RefreshTimeLine(0, 0);
                }
            }
        }

        #endregion

        #region 手势处理

        /// <summary>
        /// 手势开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GestureListener_DragStarted(object sender, DragStartedGestureEventArgs e)
        {
            // 垂直滚动
            if (e.Direction.ToString().Equals("Vertical"))
            {
                isVerticalDrag = true;
            }
        }

        /// <summary>
        /// 手势完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GestureListener_GestureCompleted(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            if (isVerticalDrag || AppSetting.HightDragSensitivity)
            {
                var scrollViewer = AppSetting.FindChildOfType<ScrollViewer>(UserDetailStatusList);
                if (null == scrollViewer)
                {
                    return;
                }
                // 到底部
                if (Math.Abs(scrollViewer.VerticalOffset - scrollViewer.ScrollableHeight) < 2)
                {
                    pollType = EPollType.NextPage;
                    // 请求新数据
                    RefreshTimeLine(PageFlag.Down, lastTimestamp);
                }
                // 到顶部
                else if (scrollViewer.VerticalOffset < 0.000001)
                {
                    pollType = EPollType.Lastest;
                    // 请求新数据
                    RefreshTimeLine(PageFlag.First, firstTimestamp);
                }
            }
        }

        #endregion

        #region 微博列表操作

        /// <summary>
        /// 转播TAP事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            MenuItem item = (MenuItem)sender;
            if (null != item)
            {
                string id = item.Tag.ToString();
                Status status = getSelectedMenuStatus(id);
                if (null != status)
                {
                    IsoSetting.Set(IsoHelper.FatherStatusKey, status);
                    NavigationService.Navigate(new Uri(string.Format("/UserControler/AddStatus.xaml?{0}={1}", AppSetting.AddStatusTypeKey, (int)AddStatusType.ReAdd.GetHashCode()), UriKind.Relative));
                }
            }
        }

        /// <summary>
        /// 回复TAP事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            MenuItem item = (MenuItem)sender;
            if (null != item)
            {
                string id = item.Tag.ToString();
                Status status = getSelectedMenuStatus(id);
                if (null != status)
                {
                    IsoSetting.Set(IsoHelper.FatherStatusKey, status);
                    NavigationService.Navigate(new Uri(string.Format("/UserControler/AddStatus.xaml?{0}={1}", AppSetting.AddStatusTypeKey, (int)AddStatusType.Reply.GetHashCode()), UriKind.Relative));
                }
            }
        }

        /// <summary>
        /// 收藏TAP事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_Tap_2(object sender, System.Windows.Input.GestureEventArgs e)
        {
            MenuItem item = (MenuItem)sender;
            string id = item.Tag.ToString();
        }

        /// <summary>
        /// 列表行TAP事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserDetailStatusList_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var listData = (IEnumerable<Status>)UserDetailStatusList.ItemsSource;
            if (null != listData)
            {
                Status status = (listData.ToList())[UserDetailStatusList.SelectedIndex] as Status;
                if (null != status)
                {
                    string commentRootId = status.Id;
                    if (!string.IsNullOrWhiteSpace(commentRootId))
                    {
                        NavigationService.Navigate(new Uri(string.Format("/UserControler/WeiboDetailPage.xaml?{0}={1}", AppSetting.CommentsListTypeKey, commentRootId), UriKind.Relative));
                    }
                }
            }
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 获取弹出菜单所处位置的微博信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private Status getSelectedMenuStatus(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                var listData = (IEnumerable<Status>)UserDetailStatusList.ItemsSource;
                if (null != listData)
                {
                    return listData.Where(t => t.Id == id).FirstOrDefault();
                }
                else
                {
                    return null;
                }
            }
            return null;
        }

        #endregion
    }
}